﻿using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using RuTracker.Interface;
using RuTrackerLib.ServiceAttibutes;

namespace RuTrackerLib.Web
{
    [PerCallService]
    public class WebClientEx : WebClient, IWebClient
    {
        private readonly ICookiesContainer _cookiesContainer;

        public WebClientEx(ICookiesContainer cookiesContainer)
        {
            _cookiesContainer = cookiesContainer;
            Encoding = Encoding.GetEncoding(1251);
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = _cookiesContainer.Container;
            }
            return request;
        }

        protected override WebResponse GetWebResponse(WebRequest request)
        {
            //return base.GetWebResponse(request);
            WebResponse response = base.GetWebResponse(request);

            if (response is HttpWebResponse)
            {
                HttpWebResponse webResponse = response as HttpWebResponse;
                _cookiesContainer.Container.Add(webResponse.Cookies);
            }

            return response;
        }

        public new string UploadValues(string address, NameValueCollection data)
        {
            byte[] buffer = base.UploadValues(address, data);
            return Encoding.GetString(buffer);

        }

        public byte[] UploadBinaryValues(string address, NameValueCollection data)
        {
            return base.UploadValues(address, data);
        }
    }
}
